//
//  FoodFetcher.mm
//  Meal Wheel
//
//  Created by Justin Dell on 6/29/08.
//  Copyright 2008 . All rights reserved.
//

#import "FoodFetcher.h"
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

// Global variables
XMLParse *parser;
string path;

// Used by the functions to get a random number between 0 and size
int getRandomNumber(int size) {
    return rand() % size;
}

@implementation FoodFetcher

-(void)initList:(char *) arg {

    // Initialize the randomizer
    srand(time(NULL));
    rand();
    
    // Traverse to Contents/Resources
    path = arg;
    int loc = path.rfind("/");
    path.resize(loc);
    loc = path.rfind("/");
    path.resize(loc);
    path.append("/Resources/foodlist.xml");
    
    // Parse the file into a food tree
    parser = [[XMLParse alloc] init];
    NSString *filename = [[NSString alloc] initWithCString:(path.c_str())];
    [parser parseXML:filename];
}

-(NSString *)getFood {
    FoodTree *foodTree = [parser getFoodTree];
    int rand = getRandomNumber(foodTree->size());
    Food *nextFood = foodTree->getFoodByIndex(rand);
    NSString *food = [[NSString alloc] initWithCString:nextFood->getName().c_str()];
    return food;
}

-(NSString *)getSpecificFood:(const char *) type {
    vector<Food *> foods = [parser getFoodTree]->getFoodsByType(type);
    int rand = getRandomNumber(foods.size());
    string name = foods[rand]->getName();
    NSString *food = [[NSString alloc] initWithCString:(name.c_str())];
    return food;
}

-(void)addFood:(string)name addType:(vector<string>)type {
    [parser getFoodTree]->addFood(name, type);
}

-(void)removeFood:(string)name {
    [parser getFoodTree]->removeFood(name);
}

-(void)writeToFile {
    [parser writeXML:(string)path];
}

-(Food *)getFoodByName:(const char *)name {
    return [parser getFoodTree]->getFoodByName(name);
}

-(vector<string>)getFoodTypes:(const char *)foodName {
    Food *food = [parser getFoodTree]->getFoodByName(foodName);
    return food->getTypes();
}

-(NSMutableArray *)getAllFoods {
    NSMutableArray *foods = [[NSMutableArray alloc] init];
    FoodTree *tree = [parser getFoodTree];
    for (int i = 0; i < tree->size(); i++) {
        [foods addObject:[[NSString alloc] initWithCString:(tree->getFoodByIndex(i)->getName().c_str())]];
    }
    
    return foods;
}

@end
